package com.mx.ymate.modbus.impl;

import com.digitalpetri.modbus.slave.ModbusTcpSlave;
import com.digitalpetri.modbus.slave.ModbusTcpSlaveConfig;
import com.mx.ymate.modbus.IModbusConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Author: xujianpeng.
 * @Date 2025/11/10.
 * @Time: 15:40.
 * @Description:
 */
public class ModbusServer {

    private final Log LOG = LogFactory.getLog(ModbusServer.class);

    private final IModbusConfig modbusConfig;

    public ModbusServer(IModbusConfig config) {
        this.modbusConfig = config;
    }

    public void start() {
        ModbusTcpSlaveConfig config = new ModbusTcpSlaveConfig.Builder().build();
        ModbusTcpSlave slave = new ModbusTcpSlave(config);

        slave.setRequestHandler(modbusConfig.serviceRequestHandler());
        int port = modbusConfig.port();
        String host = modbusConfig.host();
        try {
            slave.bind(host, port).get();
        } catch (Exception e) {
            LOG.error("Modbus TCP启动失败",e);
        }
        LOG.info("Modbus TCP从站在端口上启动 " + port);
    }
}
